package com.eques.demo.anim

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.DatePicker
import android.widget.LinearLayout
import android.widget.NumberPicker
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eques.base.BaseActivity
import com.eques.bean.WeekBean
import com.eques.database.dao.DevListDao
import com.eques.demo.R
import com.eques.demo.adapter.AnimalAdapter
import com.eques.event.EventTotalThread
import com.eques.icvss.utils.ELog
import com.eques.impl.OnClickListenerImpl
import com.eques.service.DoorBellService
import com.eques.util.BaseAppApplication
import com.eques.util.Config
import com.eques.util.EquesPreference
import com.eques.util.ObjIsEmptyUtils
import com.eques.view.PopUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONArray
import java.lang.ref.WeakReference
import java.util.Locale
import java.util.Objects


@Suppress("UNCHECKED_CAST")
class AnimalClockActivity : BaseActivity(),
    OnClickListenerImpl, DialogInterface.OnClickListener {

    private var tvMainLeftTopHint: TextView? = null
    private var tvMainTitleHint: TextView? = null
    private var constraintTimeList: ConstraintLayout? = null
    private var linSetTime: LinearLayout? = null
    private var numberPickerHour: NumberPicker? = null
    private var numberPickerMinutes: NumberPicker? = null
    private var constraintParent: ConstraintLayout? = null
    private var recWeek: RecyclerView? = null
    private var tvMainRightTopHint: TextView? = null
    private var tvFoodNumber: TextView? = null
    private var recData: RecyclerView? = null


    private var popUtils: PopUtils? = null
    private var weekBeans: List<WeekBean>? = null
    private var equesPreference: EquesPreference? = null
    private var lockId: String? = null
    private var devType: Int? = null
    private var adapter: AnimalAdapter? = null
    private var animalPlanAdapter: AnimalAdapter? = null
    var planList: MutableList<String>? = null
    private var hour: Int = 0
    private var pos: Int = -1
    private var minutes: Int = 0
    private var number: Int = 1
    private var workMode = 0
    private var currentCommand = -1
    private var currentPos = 0
    private var userUid: String? = null
    private var isSendCommand1: Boolean = false
    private var isSendCommand2: Boolean = false
    private var isSendCommand3: Boolean = false
    private var isSendCommand4: Boolean = false

    private var DISMISS_DIALOG = 10
    private val REQUEST_AWAKEN = 11 // 唤醒设备

    private lateinit var devDao: DevListDao
    private lateinit var userName: String
    private var stat:Int=0

    private val weeks = arrayOf(
        R.string.voice_service_monday,
        R.string.voice_service_tuesday,
        R.string.voice_service_wednesday,
        R.string.voice_service_thursday,
        R.string.voice_service_friday,
        R.string.voice_service_saturday,
        R.string.voice_service_sunday
    )

    private val mHandler = MyHandler(WeakReference(this))

    inner class MyHandler(private val wrActivity: WeakReference<AnimalClockActivity>) :
        Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val activity = wrActivity.get()
            when (msg.what) {
                DISMISS_DIALOG -> {
                    stopProgressDialog()
                }

                REQUEST_AWAKEN -> {
                    DoorBellService.icvss!!.equesT1WakeUpScreen(activity!!.lockId, 2, 1)
                    sendEmptyMessageDelayed(REQUEST_AWAKEN, 1000)
                }
            }
        }
    }

    private val weeksValue = arrayOf(
        "0", "0", "0", "0", "0", "0", "0"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_animal_clock_main)
        EventBus.getDefault().register(this@AnimalClockActivity)
        initData()
        init()
        initView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefreshEvent(event: EventTotalThread) {
        when (event.refresh) {
            Config.EVENT_REFRESH_GET_PLAN_SUCCES -> {
                stopProgressDialog()
                initFoodAdapter(event.stringMsg!!)
            }

            Config.EVENT_REFRESH_SEND_FOOD_PLAN_SUCCES -> {
                when (event.intMsg) {
                    0 -> {
//                        hideLoading()
                        ELog.showToast(
                            this,
                            getString(R.string.animal_send_paln_success),
                            Toast.LENGTH_SHORT
                        )
                        DoorBellService.icvss!!.equesGetAnimalDeviceInfo(userUid, lockId, devType!!)
                    }
                }

            }

            Config.EVENT_DEVICE_LIST_REFRESH -> {
                stopProgressDialog()
                //列表刷新
                CoroutineScope(Dispatchers.IO).launch {
                    var status = 1 // 默认在线
                    val buddyInfo = devDao.getBdyListEntry(userName, lockId!!)
                    status = buddyInfo.stat
                    if (status == Config.DEVICE_ONLINE) {
                        mHandler.removeMessages(REQUEST_AWAKEN)
                        sendCommand()
                    }
                }
            }

        }
    }


    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeMessages(REQUEST_AWAKEN)
        EventBus.getDefault().unregister(this@AnimalClockActivity)
    }


    override fun initView() {
        tvMainLeftTopHint = findViewById(R.id.tv_main_left_top_hint)
        tvMainTitleHint = findViewById(R.id.tv_main_title_hint)
        constraintTimeList = findViewById(R.id.constraint_time_list)
        linSetTime = findViewById(R.id.lin_set_time)
        numberPickerHour = findViewById(R.id.numberPicker_hour)
        numberPickerMinutes = findViewById(R.id.numberPicker_minutes)
        constraintParent = findViewById(R.id.constraint_root)
        recWeek = findViewById(R.id.rec_week)
        tvMainRightTopHint = findViewById(R.id.tv_main_right_top_hint)
        tvFoodNumber = findViewById(R.id.tv_food_number)
        recData = findViewById(R.id.rec_data)

        tvFoodNumber?.text = number.toString()
        popUtils = PopUtils(this)

        numberPickerHour?.setOnValueChangedListener(NumberPicker.OnValueChangeListener { picker, oldVal, newVal ->
            hour = newVal
        })
        val datas = arrayOf("0","5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55")
        numberPickerMinutes?.setOnValueChangedListener(NumberPicker.OnValueChangeListener { picker, oldVal, newVal ->
            minutes = Integer.parseInt(datas[newVal])
        })
//        numberPickerMinutes.setFormatter(NumberPicker.Formatter { value -> value.toString() })
        numberPickerHour?.value = 0
        numberPickerHour?.maxValue = 23
        numberPickerHour?.minValue = 0

        numberPickerMinutes?.displayedValues = datas //设置文字
        numberPickerMinutes?.descendantFocusability = DatePicker.FOCUS_BEFORE_DESCENDANTS
        numberPickerMinutes?.value = 0
        numberPickerMinutes?.maxValue = datas.size - 1
        numberPickerMinutes?.minValue = 0

        initTitleView()

        initAdapter()

    }

    override fun initData() {
        devDao = BaseAppApplication.instance!!.getYkDao(this)
        userName = preference.getString(Config.EQUES_USER_NAME)!!
    }

    private fun initFoodAdapter(data: String) {
        Log.e("返回结果", data)
        val jsonArray = JSONArray(data)
        planList = mutableListOf()
        for (i in 0 until jsonArray.length()) {
            planList!!.add(jsonArray.getString(i))
        }
        animalPlanAdapter = AnimalAdapter(this, planList as List<Objects>, 1)
        animalPlanAdapter?.setOnItemClickListener(this)
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        recData?.layoutManager = linearLayoutManager
        recData?.adapter = animalPlanAdapter
    }

    private fun initAdapter() {
        weekBeans = ArrayList()
        for (i in weeks.indices) {
            val weekBean = WeekBean()
            weekBean.isChoose = true
            weekBean.name = resources.getString(weeks[i])
            weekBean.index = i
            weeksValue[i] = "1"
            (weekBeans as ArrayList<WeekBean>).add(weekBean)
        }

        var linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        recWeek?.layoutManager = linearLayoutManager
        adapter = AnimalAdapter(this, weekBeans as List<Objects>, 0)
        adapter?.setOnItemClickListener(this)
        recWeek?.adapter = adapter
    }

    private fun wakeUp() {
        mHandler.sendEmptyMessage(REQUEST_AWAKEN)
        createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
        mHandler.sendEmptyMessageDelayed(DISMISS_DIALOG, 10 * 1000)
    }


    fun viewClick(view: View) {
        when (view.id) {
            R.id.img_add_food -> {
                if (constraintTimeList!!.isShown) {
                    constraintTimeList?.visibility = View.GONE
                    linSetTime?.visibility = View.VISIBLE
                    tvMainRightTopHint!!.visibility = View.VISIBLE
                }
            }

            R.id.constraint_animal_food_num -> {
                popUtils!!.setView(constraintParent)
                    .setOutsideTouchable(true)
                    .setFoodType(2)
                    .initShowPop(PopUtils.SEND_FOOD)
            }
        }
    }

    fun sendFood(value: Int) {

        number = value
        tvFoodNumber?.text = number.toString()
    }

    /**
     * 初始化头部标题栏
     */
    private fun initTitleView() {
        tvMainLeftTopHint!!.visibility = View.VISIBLE
        tvMainLeftTopHint?.setCompoundDrawablesWithIntrinsicBounds(
            resources.getDrawable(R.mipmap.ic_invitation_menu),
            null,
            null,
            null
        )
        tvMainRightTopHint?.text = getString(R.string.save)
        tvMainRightTopHint!!.setTextColor(resources.getColor(R.color.common_color_ff7316))

        tvMainTitleHint!!.visibility = View.VISIBLE
        tvMainTitleHint!!.text = getString(R.string.animal_add_clock)
        tvMainTitleHint!!.setTextColor(resources.getColor(R.color.common_color_333333))
        tvMainLeftTopHint?.setOnClickListener {
            if (linSetTime!!.isShown) {
                constraintTimeList?.visibility = View.VISIBLE
                linSetTime?.visibility = View.GONE
                tvMainRightTopHint!!.visibility = View.GONE
            } else {
                finish()
            }
        }

        tvMainRightTopHint?.setOnClickListener {
            if(ObjIsEmptyUtils.isEmpty(planList)){
                planList = mutableListOf<String>()
            }
            if (planList!!.size >= 10) {
                showToast(getString(R.string.animal_limit))
                return@setOnClickListener
            }
            currentCommand = 3
            isSendCommand3 = false
            deviceState()
            if (stat == Config.DEVICE_ONLINE) {
                createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
                sendCommand()
            } else if (stat == Config.DEVICE_SLEEP) {
                createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
                wakeUp()
            } else {
                showToast(getString(R.string.bind_split_sleep))
            }

        }
    }

    private fun sendPlan() {
        var build = StringBuffer()
        for (value: String in weeksValue) {
            build.append(value)
        }

        if("0000000".equals(build.toString())){
            showToast(getString(R.string.animal_week_none))
            stopProgressDialog()
            return
        }

        var plan: String =
            equesMytool!!.binaryIntToHexadecimal(build.toString()) +   equesMytool!!.toHexString(hour) +
                    equesMytool!!.toHexString(minutes) +   equesMytool!!.toHexString(number) + "01"

        if (!ObjIsEmptyUtils.isEmpty(planList)) {
            Log.e("PLAN...", "...$plan")
            var isExists = false
            for (i in 0..planList!!.size - 1) {
                if (plan.lowercase(Locale.getDefault()).substring(0,6).equals(
                        planList!!.get(i).lowercase(Locale.getDefault()).subSequence(0,6))) {
                    isExists = true
                }
            }
            if (isExists) {
                showToast(getString(R.string.animal_send_agin_plan))
                stopProgressDialog()
            } else {
                planList!!.add(plan)
                val nullableStringArray = arrayOfNulls<String?>(planList!!.size)
                for (i in 0..planList!!.size - 1) {
                    nullableStringArray[i] = planList!![i]
                }
                DoorBellService.icvss!!.equesSendAnimlFoodPlan(
                    lockId,
                    nullableStringArray
                )
            }
        } else {
            DoorBellService.icvss!!.equesSendAnimlFoodPlan(
                lockId,
                arrayOf(plan)
            )
        }
        constraintTimeList?.visibility = View.VISIBLE
        linSetTime?.visibility = View.GONE
        tvMainRightTopHint!!.visibility = View.GONE
        number = 1
        tvFoodNumber?.text = number.toString()
        mHandler.sendEmptyMessageDelayed(DISMISS_DIALOG, 10 * 1000)
    }


    private fun init() {
        lockId = intent.getStringExtra(Config.BID)
        ELog.d("lockId.....", lockId)
        devType = intent.getIntExtra("devType", 0)
        equesPreference = EquesPreference(this)
        userUid = equesPreference!!.getString(Config.EQUES_USER_UID)
        currentCommand = 1
        isSendCommand1 = false
        deviceState()
        if (stat == Config.DEVICE_SLEEP) {
            wakeUp()
        } else {
            sendCommand()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun sendCommand() {
        Log.e("Command", "............currentCommand:$currentCommand")
        when (currentCommand) {
            1 -> {
                if (!isSendCommand1) {
                    isSendCommand1 = true
                    createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
                    mHandler.sendEmptyMessageDelayed(DISMISS_DIALOG, 10 * 1000)
                    DoorBellService.icvss!!.equesGetAnimalDeviceInfo(userUid, lockId, devType!!)
                }
            }

            2 -> {
                if (!isSendCommand2) {
                    isSendCommand2 = true
                    mHandler.sendEmptyMessageDelayed(DISMISS_DIALOG, 10 * 1000)
                    val nullableStringArray = arrayOfNulls<String?>(planList!!.size)
                    for (i in 0..planList!!.size - 1) {
                        nullableStringArray[i] = planList!![i]
                    }
                    DoorBellService.icvss!!.equesSendAnimlFoodPlan(
                        lockId,
                        nullableStringArray
                    )
                    animalPlanAdapter?.notifyDataSetChanged()
                }
            }

            3 -> {
                if (!isSendCommand3) {
                    isSendCommand3 = true
                    sendPlan()
                }
            }

            4->{
                if (!isSendCommand4) {
                    isSendCommand4 = true
                    planList?.removeAt(pos)
                    val nullableStringArray = arrayOfNulls<String?>(planList!!.size)
                    for (i in 0..planList!!.size - 1) {
                        nullableStringArray[i] = planList!![i]
                    }
                    DoorBellService.icvss!!.equesSendAnimlFoodPlan(
                        lockId,
                        nullableStringArray
                    )
                    animalPlanAdapter?.notifyDataSetChanged()
                }
            }

        }
    }

    private fun deviceState() {
      CoroutineScope(Dispatchers.IO).launch {
          val buddyInfo=devDao.getBdyListEntry(userName, lockId!! )
          if (buddyInfo != null) {
              stat= buddyInfo.stat
          }
      }
    }



    @SuppressLint("NotifyDataSetChanged")
    override fun CallBackItemClickListener(position: Int, voiceServiceType: Int, eventType: Int) {
        when (eventType) {
            0 -> {
                if (weekBeans?.get(position)?.isChoose == true) {
                    weekBeans?.get(position)?.isChoose = false
                    weeksValue[position] = "0"
                } else {
                    weekBeans?.get(position)?.isChoose = true
                    weeksValue[position] = "1"
                }
                adapter?.notifyDataSetChanged()
            }

            1 -> {
                if (planList!![position].substring(8, 10) == "00") {
                    planList!![position] = planList!![position].substring(0, 8) + "01"
                } else {
                    planList!![position] = planList!![position].substring(0, 8) + "00"
                }
                currentPos = position
                currentCommand = 2
                isSendCommand2 = false
                deviceState()
                if ( stat== Config.DEVICE_ONLINE) {
                    createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
                    sendCommand()
                } else {
                    createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
                    wakeUp()
                }
            }
        }
    }


    override fun LongCallBackItemClickListener(position: Int) {
        pos = position
        if (pos != -1) {
            currentCommand = 4
            isSendCommand4 = false
            deviceState()
            if ( stat== Config.DEVICE_ONLINE) {
                createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
                sendCommand()
            } else if (stat == Config.DEVICE_SLEEP) {
                createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false);
                wakeUp()
            } else {
                showToast(getString(R.string.bind_split_sleep))
            }


        }
    }

    override fun onClick(p0: DialogInterface?, p1: Int) {
    }


}